package com.glq1218.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;

/**
 * @author glq1218
 */
public class JwtUtils {

    private static final String SECRET_KEY = "ecd194d76e7533b8a0bc414394b2323251ab48acb1703a440e44d0c3e8d410a0";
    private static final long EXPIRATION_TIME = 24 * 60 * 60 * 1000;

    public static String generateJwt(String username) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    public static String getUsername(String jwt) {
        return extractAllClaims(jwt).getSubject();
    }

    public static boolean isExpired(String jwt) {
        return extractAllClaims(jwt).getExpiration().before(new Date());
    }

    private static Claims extractAllClaims(String jwt) {
        // 不管是否过期，都返回claims对象
        Claims claims;
        try {
            claims = Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }

    /**
     * 获取签名密钥
     *
     * @return SigningKey 签名密钥
     */
    private static Key getSigningKey() {
        byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
        return Keys.hmacShaKeyFor(keyBytes);
    }
}
